package com.sharecode.stock.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.sharecode.stock.annotation.AdminAnnotation;
import com.sharecode.stock.thread.ThreadLocalUtils;
import com.sharecode.stock.vo.User;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class RestResultAOP {

	@Pointcut("execution(* com.sharecode.stock.controller..*.*(..))")
	public void pointcut() {

	}

	@Around(value = "pointcut()")
	public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
		RestResult<Object> result = new RestResult<>();
		log.info(joinPoint.getSignature() + " 请求参数:" + ThreadLocalUtils.getParam());
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();

		AdminAnnotation adminAnnotation = signature.getMethod().getAnnotation(AdminAnnotation.class);
		if (adminAnnotation != null) {
			User user = (User) ThreadLocalUtils.getRequest().getSession().getAttribute("user");
			if (user.getType() != 1) {
				result.setCode(400);
				result.setMessage("请不要乱点");
				ThreadLocalUtils.getResponse().getWriter().print(JSONObject.toJSONString(result));
				return;
			}
		}
		Object proceed = joinPoint.proceed();
		if (proceed instanceof RestResult) {
			ThreadLocalUtils.getResponse().getWriter().print(JSONObject.toJSONString(proceed));
		} else {
			if (proceed != null) {
				result.setData(proceed);
			}
			ThreadLocalUtils.getResponse().getWriter().print(JSONObject.toJSONString(result));
		}
	}
}
